#region Copyright & licence

// This file is part of Refix.
// 
// Refix is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
// 
// Refix is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
// 
// You should have received a copy of the GNU Lesser General Public
// License along with Refix.  If not, see <http://www.gnu.org/licenses/>.
// 
// Copyright (C) 2010-11 David Musgrove and others.

#endregion

using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Web.Mvc;

using Refix.Core;
using Refix.Core.Repository;
using Refix.Repository.Models;
using Refix.Repository.ViewModels;

using Configuration = Refix.Core.Configuration;

namespace Refix.Repository.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        [AcceptVerbs(HttpVerbs.Get | HttpVerbs.Head)]
        public ActionResult Summary()
        {
            List<SummaryEntry> results = new RepositoryModel().GetSummary();
            return View(results);
        }

        [AcceptVerbs(HttpVerbs.Get | HttpVerbs.Head)]
        public ActionResult Index(string path)
        {
            string directory = Configuration.LocalRepository;
            if (!string.IsNullOrEmpty(path))
            {
                directory = Path.Combine(directory, path.Replace("~", "/"));
            }
            bool uploadEnabled = !string.IsNullOrEmpty(Configuration.RemoteRepository)
                                 && !string.IsNullOrEmpty(ConfigurationManager.AppSettings["Refix.Upload.Email"]);
            var directoryInfo = new DirectoryInfo(directory);
            string componentName = path.Replace("~", ".");
            Component component = new LocalRepository().GetComponent(componentName, false);
            string[] versionNumbers = component == null
                                    ? new string[0]
                                    : component.Versions.ConvertAll(v => v.Number).ToArray();
            var folders = new List<DirectoryInfo>(directoryInfo.GetDirectories()
                .Where(d => !versionNumbers.Contains(d.Name)))
                .ConvertAll(d => new BrowseEntry
                {
                    Icon = "folder",
                    Label = d.Name,
                    Url = Url.Action("Index", "Home", new { path = CombinePath(path, d.Name) })
                });
            if (!string.IsNullOrEmpty(path))
            {
                folders.Insert(0, new BrowseEntry
                                  {
                                      Icon = "folder",
                                      Label = "..",
                                      Url =
                                          Url.Action("Index", "Home", new {path = path.Contains("~") ? path.Substring(0, path.LastIndexOf("~")) : ""})
                                  });
            }
            var versions = new List<DirectoryInfo>(directoryInfo.GetDirectories()
                .Where(d => versionNumbers.Contains(d.Name)))
                .ConvertAll(d => new BrowseEntry
                {
                    Icon = "component",
                    Label = d.Name,
                    Url = Url.Action("Get", "Component", new { component = componentName, version = d.Name }),
                    UploadUrl = Url.Action("Upload", "Component", new { component = componentName, version = d.Name }),
                    CanUpload = uploadEnabled
                });
            return View(folders.Union(versions));
        }

        static private string CombinePath(string path, string name)
        {
            if (string.IsNullOrEmpty(path))
            {
                return name;
            }
            return string.Format("{0}~{1}", path, name);
        }
    }
}